package com.zengdada.authority.utils.where.result;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zsa
 * @date 2020/9/10 14:18
 */
public class AnalysisResultMerge {
    private String rel = "AND";
    private String extraFilter;
    private final List<Object> paramValues = new ArrayList<>(1);
    private String anyWhereExtraFilter;
    private final List<Object> anyWhereParamValues = new ArrayList<>(1);

    public boolean isNull() {
        return StringUtils.isAllBlank(extraFilter, anyWhereExtraFilter) && paramValues.isEmpty() && anyWhereParamValues.isEmpty();
    }

    public AnalysisResultMerge() {
    }

    public AnalysisResultMerge(AnalysisResult analysis) {
        if (analysis != null && !analysis.isNull()) {
            rel = analysis.getRel();
            paramValues.addAll(analysis.getParamValues());
            anyWhereParamValues.addAll(analysis.getAnyWhereParamValues());
            if (!analysis.getExtraFilters().isEmpty()) {
                if (analysis.getExtraFilters().size() == 1) {
                    extraFilter = analysis.getExtraFilters().get(0);
                } else {
                    extraFilter = String.format("( %s )", String.join(" " + analysis.getRel() + " ", analysis.getExtraFilters()));
                }
            }
            if (!analysis.getAnyWhereExtraFilters().isEmpty()) {
                if (analysis.getAnyWhereExtraFilters().size() == 1) {
                    anyWhereExtraFilter = analysis.getAnyWhereExtraFilters().get(0);
                } else {
                    anyWhereExtraFilter = String.format("( %s )", String.join(" " + analysis.getRel() + " ", analysis.getAnyWhereExtraFilters()));
                }
            }
        }
    }

    public List<Object> addParamValue(Object paramValue) {
        paramValues.add(paramValue);
        return paramValues;
    }

    public List<Object> addAnyWhereParamValues(Object paramValue) {
        anyWhereParamValues.add(paramValue);
        return anyWhereParamValues;
    }

    public String getRel() {
        return rel;
    }

    public String getExtraFilter() {
        return extraFilter;
    }

    public List<Object> getParamValues() {
        return paramValues;
    }

    public void setExtraFilter(String extraFilter) {
        this.extraFilter = extraFilter;
    }

    public String getAnyWhereExtraFilter() {
        return anyWhereExtraFilter;
    }

    public List<Object> getAnyWhereParamValues() {
        return anyWhereParamValues;
    }
}
